﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetExtensions.AspNet.SQLites
{
    public class QueryConditionResolver<T> : BaseConditionResolver<T>
    {
        public QueryConditionResolver(string prefix = "$") : base(prefix)
        { }

        public QueryConditionResolver(TableInfo entity, string prefix = "$") : base(entity, prefix)
        { }

        protected override string ResolveStackToField(Stack<string> parameterStack)
        {
            switch (parameterStack.Count)
            {
                case 2:
                    {
                        // 调用了导航属性
                        var propertyName = parameterStack.Pop();
                        var propertyFieldName = parameterStack.Pop();

                        TableInfo propertyEntity = Result.NavPropertyList.SingleOrDefault(p => p.OriginName == propertyName);
                        if (propertyEntity == null)
                        {
                            var prop = Entity.Properties.Single(p => p.OriginName == propertyName);
                            propertyEntity = TableInfoFactory.Default.Get(prop.Type);
                            Result.NavPropertyList.Add(propertyEntity);
                        }

                        var propertyProperty = propertyEntity.Properties.Single(p => p.OriginName == propertyFieldName);
                        return $"[{propertyName}].[{propertyProperty.Name}]";
                    }
                case 1:
                    {
                        var propertyName = parameterStack.Pop();
                        var propInfo = Entity.Properties.Single(p => p.OriginName == propertyName);
                        return $"{propInfo.Name}";
                    }
                default:
                    throw new ArgumentException("尚未支持大于2层属性调用。如 student.Clazz.School.Id>10，请使用类似 student.Clazz.SchoolId > 0 替代");
            }
        }
    }
}
